package com.jmpt.fangbohui.ui;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.Intents.UI;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.BrokerShopBean;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.ApiUrl;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.ui.fragment.BrokerShopHouseListFragment;
import com.jmpt.fangbohui.ui.fragment.BrokerShopOldHouseListFragment;
import com.jmpt.fangbohui.ui.fragment.BrokerShopRentHouseListFragment;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.jmpt.fangbohui.view.TabSlidingIndicator;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * @包名:  com.jmpt.fangbohui.ui
 * @类名:  BrokerShopActivity
 * @作者:  China_Victor 724932439#qq.com
 * @创建时间 : 2015-9-1 下午2:35:33
 *
 * @描述: 经纪人网店详情
 */
public class BrokerShopActivity extends BaseHeadActivity {

	/*
	 * phone : 18998151801 
	 * username : 于涌生 
	 * picUrl : http://www.cnfbh.com/uploads/head_agent/fbh_201508151635188725.jpg
	 * zjcname : 自由经纪人
	 */
	
	public static String UID_EXTRA_KEY = "uid_extra_key";
	public static String PHONE_EXTRA_KEY = "phone_extra_key";
	public static String USERNAME_EXTRA_KEY = "username_extra_key";
	public static String PICURL_EXTRA_KEY = "picurl_extra_key";
	public static String ZJCNAME_EXTRA_KEY = "zjcname_extra_key";
	
	private String uid;
	private String phone;
	private String username;
	private String picUrl;
	private String zjcname;
	
	@ViewInject(R.id.iv_broker_pic)
	private ImageView IvPic;
	
	@ViewInject(R.id.tv_broker_name)
	private TextView mTvName;
	
	@ViewInject(R.id.tv_broker_tel)
	private TextView mTvTel;
	
	@ViewInject(R.id.tv_broker_com)
	private TextView mTvCompany;
	
	@ViewInject(R.id.id_stickynavlayout_indicator)
	private TabSlidingIndicator mIndicator;
	
	@ViewInject(R.id.id_stickynavlayout_viewpager)
	private ViewPager mViewPager;
	
	private BrokerShopBean mShopData;
	
	private FragmentPagerAdapter pagerAdapter;
	
	private Map<Integer, Fragment> fragmentPageList = new HashMap<Integer, Fragment>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		initExtraData();
		
		showTitle("经纪人网店");

		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		setContentView(R.layout.activity_broker_shop);
		
		ViewUtils.inject(this);
		
		initView();
		
		loadData();
		
	}

	private void initView() {
		mTvTel.setText("买卖/出租热线：" + phone);
		mTvName.setText(username);
		mTvCompany.setText(zjcname);
		ImageLoaderHelper.displayImage(picUrl, IvPic);
		
	}

	private void initExtraData() {
		Intent intent = getIntent();
		if(intent == null){
			return;
		}
		
		uid = intent.getStringExtra(UID_EXTRA_KEY);
		phone = intent.getStringExtra(PHONE_EXTRA_KEY);
		username = intent.getStringExtra(USERNAME_EXTRA_KEY);
		picUrl = intent.getStringExtra(PICURL_EXTRA_KEY);
		zjcname = intent.getStringExtra(ZJCNAME_EXTRA_KEY);
		
	}
	
	@SuppressWarnings("deprecation")
	@OnClick(R.id.rl_broker_shop_contact)
	public void call(View view){
        if (TextUtils.isEmpty(phone)) {
            ToastHelper.ShowToast("该商家没有电话号码", UIUtils.getContext());
            return;
        }

        Builder builder = new AlertDialog.Builder(this);
        final AlertDialog alertDialog = builder.create();
        
        alertDialog.setTitle("拨打电话");
        alertDialog.setMessage(phone);
        alertDialog.setButton("拨打", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
            	BrokerShopActivity.this.startActivity(intent);
				alertDialog.dismiss();
			}
		});
        alertDialog.setButton2("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				alertDialog.dismiss();
			}
		});
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
	}
	

	private void loadData() {
		addRequestHandle(ApiRequest.getBrokerShopDetail(uid, new JsonHttpHandler(this){
			
			@Override
			public void onStart() {
				setShowProgressDialog("正在加载中...");
				super.onStart();
			}
			
			@Override
			public void onDo(JSONObject response) {
				DebugLog.i(response.toString());
				try {
					mShopData = new Gson().fromJson(response.toString(), BrokerShopBean.class);
					refreshUI();
				} catch (Exception e) {
					e.printStackTrace();
					ToastHelper.ShowToast("网店数据获取失败，请稍后再试试...", UIUtils.getContext());
				}
			}
		}));
	}

	protected void refreshUI() {
		
		pagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return getTabFragment(position);
            }
            
            private String[] titles = new String[]{"精选房源","热推二手房","热推租房"};
            
            @Override
            public CharSequence getPageTitle(int position) {
            	return titles[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }
        };
        
		mViewPager.setAdapter(pagerAdapter);
		
		mIndicator.setViewPager(mViewPager);
		
		mViewPager.setOnTouchListener(new View.OnTouchListener() {
            float startX;
            float startY;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = motionEvent.getX();
                        startY = motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float dx = motionEvent.getX() - startX;
                        float dy = motionEvent.getY() - startY;
                        if (Math.abs(dx) > Math.abs(dy)) {
                        	mViewPager.getParent().requestDisallowInterceptTouchEvent(true);
                        	mViewPager.getParent().getParent().requestDisallowInterceptTouchEvent(true);
                        }
                        break;
                }
                return false;
            }
        });
		
		mViewPager.setCurrentItem(0);
	}
	
	private Fragment getTabFragment(int position) {
		Fragment basePageFragment = fragmentPageList.get(position);
        if (basePageFragment == null) {
            switch (position) {
                case 0:
                    basePageFragment = new BrokerShopHouseListFragment();
                    ((BrokerShopHouseListFragment) basePageFragment).setData(mShopData.HouseInfo, uid);
                    break;
                case 1:
                    basePageFragment = new BrokerShopOldHouseListFragment();
                    ((BrokerShopOldHouseListFragment) basePageFragment).setData(mShopData.hot_eshouse, uid);
                    break;
                case 2:
                    basePageFragment = new BrokerShopRentHouseListFragment();
                    ((BrokerShopRentHouseListFragment) basePageFragment).setData(mShopData.hot_renthouse, uid);
                    break;
            }
            fragmentPageList.put(position, basePageFragment);
        }
        return basePageFragment;
    }

}
